package com.rimi.shiro;

import com.alibaba.fastjson.JSONObject;
import com.rimi.commons.CommonResult;
import com.rimi.commons.ResultStatus;
import org.apache.shiro.web.filter.authc.BearerHttpAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author luc
 * @Date 2021/7/2
 */
public class BearerFilter extends BearerHttpAuthenticationFilter {

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        return false;
    }

    @Override
    protected boolean sendChallenge(ServletRequest request, ServletResponse response) {

        HttpServletResponse resp = (HttpServletResponse)response;

        resp.addHeader("Access-Control-Allow-Origin","*");
        resp.addHeader("Access-Control-Allow-Headers","*");
        resp.addHeader("Access-Control-Allow-Methods","*");
        resp.addHeader("Access-Control-Expose-Headers","*");

        resp.setCharacterEncoding("utf-8");
        try {
            resp.getWriter().append(JSONObject.toJSONString(CommonResult.onFailed(ResultStatus.AUTH_FAILED)));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}
